// stores/modules/hardware.js - 硬件设备模块状态管理
import { defineStore } from 'pinia'
import api from '@/api/modules'
import { message } from '@/utils'

export const useHardwareStore = defineStore('hardware', {
  state: () => ({
    deviceRegistrations: [],       // 已注册的设备列表
    currentHardwareId: null,       // 当前操作的硬件ID
    firmwareVersions: [],          // 固件版本列表
    deviceTypes: [],               // 设备类型列表
    deviceStatus: null,            // 当前设备状态
    deviceConfig: null,            // 当前设备配置
    deviceLogs: [],                // 设备日志
    deviceNetworkInfo: null,       // 设备网络信息
    connectionHistory: [],         // 连接历史
    isUpdatingFirmware: false,     // 固件更新状态
    registrationLoading: false,    // 注册加载状态
    lastRegisteredDevice: null,    // 最后注册的设备信息
    pendingCommands: []            // 待发送的命令队列
  }),
  
  getters: {
    // 获取当前设备注册信息
    getCurrentRegistration: (state) => {
      if (!state.currentHardwareId) return null
      return state.deviceRegistrations.find(device => device.id === state.currentHardwareId)
    },
    
    // 设备是否在线
    isDeviceOnline: (state) => {
      return state.deviceStatus && state.deviceStatus.online
    },
    
    // 获取设备连接状态
    connectionStatus: (state) => {
      if (!state.deviceStatus) return 'unknown'
      return state.deviceStatus.online ? 'online' : 'offline'
    },
    
    // 是否有固件更新
    hasFirmwareUpdate: (state) => {
      if (!state.deviceStatus || !state.deviceStatus.firmwareVersion) return false
      const currentVersion = state.deviceStatus.firmwareVersion
      const latestVersion = state.firmwareVersions[0]?.version
      return latestVersion && currentVersion !== latestVersion
    },
    
    // 获取设备WIFI信号强度
    wifiSignalStrength: (state) => {
      if (!state.deviceNetworkInfo) return 0
      return state.deviceNetworkInfo.wifiSignal || 0
    }
  },
  
  actions: {
    // 设置当前硬件ID
    setCurrentHardwareId(id) {
      this.currentHardwareId = id
      this.deviceStatus = null
      this.deviceConfig = null
      this.deviceLogs = []
      this.deviceNetworkInfo = null
    },
    
    // 在hardware.js store的actions部分添加
    async registerDevice(deviceParams) {
      try {
        this.registrationLoading = true;
        
        // 准备注册所需参数
        const registrationData = {
          productId: deviceParams.productId,
          macAddress: this.formatMacAddress(deviceParams.macAddress),
          firmwareVersion: deviceParams.firmwareVersion || 'V1.0.0',
          ipAddress: deviceParams.ipAddress || '',
          wifiSsid: deviceParams.wifiSsid || '',
          wifiSignal: deviceParams.wifiSignal || -80
        };
        
        // 先检查设备是否已经注册
        const checkResult = await api.hardware.checkMacAddress(registrationData.macAddress);
        
        if (checkResult.code === 200 && checkResult.data) {
          // 获取设备详情
          const deviceInfo = await api.hardware.getDeviceByMac(registrationData.macAddress);
          
          if (deviceInfo.code === 200 && deviceInfo.data) {
            const currentUserId = parseInt(uni.getStorageSync('userId'));
            const deviceUserId = deviceInfo.data.userId;
            
            // 如果设备已绑定到其他用户，抛出错误
            if (deviceUserId && deviceUserId !== currentUserId) {
              const error = new Error(`设备已被用户ID为 ${deviceUserId} 的用户绑定，无法重复添加`);
              // 添加自定义属性，便于前端处理
              error.boundUserId = deviceUserId;
              throw error;
            }
            
            // 如果设备已经绑定到当前用户，直接返回设备信息
            if (deviceUserId && deviceUserId === currentUserId) {
              this.lastRegisteredDevice = deviceInfo.data;
              return this.lastRegisteredDevice;
            }
          }
        }
        
        // 设备不存在或无法更新，执行正常注册流程
        const res = await api.hardware.registerDevice(registrationData);
        
        if (res.code === 200 && res.data) {
          this.lastRegisteredDevice = res.data;
          this.deviceRegistrations.push(res.data);
          return res.data;
        } else {
          throw new Error(res.message || '设备注册失败');
        }
      } catch (error) {
        console.error('设备注册处理失败:', error);
        throw error;
      } finally {
        this.registrationLoading = false;
      }
    },
	
	// 配置设备智能体
	async configureDeviceAgent(hardwareMac, smartDeviceId) {
	  try {
	    uni.showLoading({
	      title: '正在配置设备...',
	      mask: true
	    });
	    
	    // 调用新的API配置设备
	    const res = await api.hardware.configureDeviceAI(hardwareMac, smartDeviceId);
	    
	    if (res.code === 200) {
	      // 更新本地存储
	      try {
	        // 将MAC地址格式化为一致格式
	        const formattedMac = this.formatMacAddress(hardwareMac);
	        
	        // 存储最新的配置信息
	        let configuredDevices = uni.getStorageSync('configuredDevices') || {};
	        configuredDevices[formattedMac] = smartDeviceId;
	        uni.setStorageSync('configuredDevices', configuredDevices);
	      } catch (e) {
	        console.error('Failed to store configuration in local storage:', e);
	      }
	      
	      uni.hideLoading();
	      message.success('设备AI配置成功');
	      return true;
	    } else {
	      throw new Error(res.message || '设备AI配置失败');
	    }
	  } catch (error) {
	    uni.hideLoading();
	    console.error('配置设备AI失败:', error);
	    message.error(error.message || '配置设备AI失败');
	    return false;
	  }
	},
	
	// 清除设备智能体配置
	async clearDeviceAgent(hardwareMac) {
	  try {
	    uni.showLoading({
	      title: '正在清除配置...',
	      mask: true
	    });
	    
	    // 调用新的API清除配置
	    const res = await api.hardware.clearDeviceAI(hardwareMac);
	    
	    if (res.code === 200) {
	      // 更新本地存储
	      try {
	        const formattedMac = this.formatMacAddress(hardwareMac);
	        
	        // 从本地存储中移除配置信息
	        let configuredDevices = uni.getStorageSync('configuredDevices') || {};
	        delete configuredDevices[formattedMac];
	        uni.setStorageSync('configuredDevices', configuredDevices);
	      } catch (e) {
	        console.error('Failed to remove configuration from local storage:', e);
	      }
	      
	      uni.hideLoading();
	      message.success('设备AI配置已清除');
	      return true;
	    } else {
	      throw new Error(res.message || '清除设备AI配置失败');
	    }
	  } catch (error) {
	    uni.hideLoading();
	    console.error('清除设备AI配置失败:', error);
	    message.error(error.message || '清除设备AI配置失败');
	    return false;
	  }
	},
	
	// 获取设备当前智能体ID
	async getCurrentDeviceAgent(hardwareMac) {
	  try {
	    // 调用新的API获取当前配置
	    const res = await api.hardware.getCurrentDeviceAI(hardwareMac);
	    
	    if (res.code === 200 && res.data) {
	      return res.data.smartDeviceId;
	    }
	    return null;
	  } catch (error) {
	    console.error('获取设备当前智能体失败:', error);
	    return null;
	  }
	},
	
	// 格式化MAC地址工具方法
	formatMacAddress(macAddress) {
	  if (!macAddress) return '';
	  
	  // 移除所有分隔符
	  let mac = macAddress.replace(/[:-]/g, '').toLowerCase();
	  
	  // 如果已经是规范格式，直接返回
	  if (macAddress.includes(':') && macAddress.length === 17) {
	    return macAddress.toLowerCase();
	  }
	  
	  // 插入冒号
	  let formattedMac = '';
	  for (let i = 0; i < mac.length; i++) {
	    if (i > 0 && i % 2 === 0) {
	      formattedMac += ':';
	    }
	    formattedMac += mac.charAt(i);
	  }
	  
	  return formattedMac;
	},
	
	// 获取用户已注册的设备列表
	async getDeviceRegistrations() {
	  try {
	    // 获取本地存储的用户ID
	    const userId = uni.getStorageSync('userId');
	    if (!userId) {
	      console.warn('未找到用户ID，无法获取设备列表');
	      return [];
	    }
	    
	    // 使用getUserDevices方法获取设备列表
	    const res = await api.hardware.getUserDevices(userId);
	    
	    if (res.code === 200 && res.data && res.data.records) {
	      this.deviceRegistrations = res.data.records;
	      
	      // If we have devices, set the last registered device
	      if (this.deviceRegistrations.length > 0) {
	        // Sort by registration time if available, otherwise use the first one
	        const sortedDevices = [...this.deviceRegistrations].sort((a, b) => {
	          if (a.createdAt && b.createdAt) {
	            return new Date(b.createdAt) - new Date(a.createdAt);
	          }
	          return 0;
	        });
	        
	        this.lastRegisteredDevice = sortedDevices[0];
	      }
	      
	      return this.deviceRegistrations;
	    }
	    return [];
	  } catch (error) {
	    console.error('获取设备注册列表失败:', error);
	    return [];
	  }
	},
    
    // 获取设备状态
    async getDeviceStatus(deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) return null
      
      try {
        const res = await api.hardware.getDeviceStatus(id)
        if (res.code === 200) {
          this.deviceStatus = res.data
          return res.data
        }
        return null
      } catch (error) {
        console.error('获取设备状态失败:', error)
        return null
      }
    },
    
    // 获取设备网络信息
    async getNetworkInfo(deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) return null
      
      try {
        const res = await api.hardware.getNetworkInfo(id)
        if (res.code === 200) {
          this.deviceNetworkInfo = res.data
          return res.data
        }
        return null
      } catch (error) {
        console.error('获取设备网络信息失败:', error)
        return null
      }
    },
    
    // 获取设备配置
    async getDeviceConfig(deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) return null
      
      try {
        const res = await api.hardware.getDeviceConfig(id)
        if (res.code === 200) {
          this.deviceConfig = res.data
          return res.data
        }
        return null
      } catch (error) {
        console.error('获取设备配置失败:', error)
        return null
      }
    },
    
    // 更新设备配置
    async updateDeviceConfig(config, deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) {
        message.error('未指定设备ID')
        return false
      }
      
      try {
        const res = await api.hardware.updateDeviceConfig(id, config)
        if (res.code === 200) {
          // 更新本地缓存的配置
          this.deviceConfig = res.data || config
          message.success('设备配置更新成功')
          return true
        } else {
          message.error(res.message || '设备配置更新失败')
          return false
        }
      } catch (error) {
        console.error('更新设备配置失败:', error)
        message.error('设备配置更新失败')
        return false
      }
    },
    
    // 获取设备日志
    async getDeviceLogs(deviceId = null, params = { page: 1, size: 20 }) {
      const id = deviceId || this.currentHardwareId
      if (!id) return []
      
      try {
        const res = await api.hardware.getDeviceLogs(id, params)
        if (res.code === 200) {
          if (params.page === 1) {
            this.deviceLogs = res.data.records || []
          } else {
            // 追加日志
            this.deviceLogs = [...this.deviceLogs, ...(res.data.records || [])]
          }
          return res.data
        }
        return []
      } catch (error) {
        console.error('获取设备日志失败:', error)
        return []
      }
    },
    
    // 获取固件版本列表
    async getFirmwareVersions() {
      try {
        const res = await api.hardware.getFirmwareList()
        if (res.code === 200) {
          this.firmwareVersions = res.data || []
          return res.data
        }
        return []
      } catch (error) {
        console.error('获取固件版本列表失败:', error)
        return []
      }
    },
    
    // 检查固件更新
    async checkFirmwareUpdate(deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) return null
      
      try {
        const res = await api.hardware.checkFirmwareUpdate(id)
        if (res.code === 200) {
          return res.data
        }
        return null
      } catch (error) {
        console.error('检查固件更新失败:', error)
        return null
      }
    },
    
    // 更新固件
    async updateFirmware(deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) {
        message.error('未指定设备ID')
        return false
      }
      
      try {
        this.isUpdatingFirmware = true
        const res = await api.hardware.updateFirmware(id)
        if (res.code === 200) {
          message.success('固件更新任务已启动')
          return true
        } else {
          message.error(res.message || '固件更新失败')
          return false
        }
      } catch (error) {
        console.error('固件更新失败:', error)
        message.error('固件更新失败')
        return false
      } finally {
        this.isUpdatingFirmware = false
      }
    },
    
    // 重启设备
    async restartDevice(deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) {
        message.error('未指定设备ID')
        return false
      }
      
      try {
        const res = await api.hardware.restartDevice(id)
        if (res.code === 200) {
          message.success('设备重启命令已发送')
          return true
        } else {
          message.error(res.message || '设备重启失败')
          return false
        }
      } catch (error) {
        console.error('设备重启失败:', error)
        message.error('设备重启失败')
        return false
      }
    },
    
    // 重置设备
    async resetDevice(deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) {
        message.error('未指定设备ID')
        return false
      }
      
      try {
        const res = await api.hardware.resetDevice(id)
        if (res.code === 200) {
          message.success('设备重置命令已发送')
          return true
        } else {
          message.error(res.message || '设备重置失败')
          return false
        }
      } catch (error) {
        console.error('设备重置失败:', error)
        message.error('设备重置失败')
        return false
      }
    },
    
    // 绑定设备到当前用户
    async bindDevice(deviceData) {
      try {
        const res = await api.hardware.bindDevice(deviceData)
        if (res.code === 200) {
          message.success('设备绑定成功')
          return res.data
        } else {
          message.error(res.message || '设备绑定失败')
          return null
        }
      } catch (error) {
        console.error('设备绑定失败:', error)
        message.error('设备绑定失败')
        return null
      }
    },
    
    // 解绑设备
    async unbindDevice(deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) {
        message.error('未指定设备ID')
        return false
      }
      
      try {
        const res = await api.hardware.unbindDevice(id)
        if (res.code === 200) {
          message.success('设备解绑成功')
          return true
        } else {
          message.error(res.message || '设备解绑失败')
          return false
        }
      } catch (error) {
        console.error('设备解绑失败:', error)
        message.error('设备解绑失败')
        return false
      }
    },
    
    // 获取连接历史
    async getConnectionHistory(deviceId = null, params = { page: 1, size: 20 }) {
      const id = deviceId || this.currentHardwareId
      if (!id) return []
      
      try {
        const res = await api.hardware.getConnectionHistory(id, params)
        if (res.code === 200) {
          if (params.page === 1) {
            this.connectionHistory = res.data.records || []
          } else {
            // 追加历史记录
            this.connectionHistory = [...this.connectionHistory, ...(res.data.records || [])]
          }
          return res.data
        }
        return []
      } catch (error) {
        console.error('获取连接历史失败:', error)
        return []
      }
    },
    
    // 获取设备类型列表
    async getDeviceTypes() {
      try {
        if (this.deviceTypes.length > 0) {
          return this.deviceTypes
        }
        
        const res = await api.hardware.getDeviceTypes()
        if (res.code === 200) {
          this.deviceTypes = res.data || []
          return res.data
        }
        return []
      } catch (error) {
        console.error('获取设备类型列表失败:', error)
        return []
      }
    },
    
    // 获取设备统计信息
    async getDeviceStats(deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) return null
      
      try {
        const res = await api.hardware.getDeviceStats(id)
        if (res.code === 200) {
          return res.data
        }
        return null
      } catch (error) {
        console.error('获取设备统计信息失败:', error)
        return null
      }
    },
    
    // 发送设备命令
    async sendCommand(command, deviceId = null) {
      const id = deviceId || this.currentHardwareId
      if (!id) {
        message.error('未指定设备ID')
        return false
      }
      
      try {
        // 添加到命令队列
        this.pendingCommands.push({
          deviceId: id,
          command,
          status: 'pending',
          timestamp: Date.now()
        })
        
        const res = await api.hardware.sendCommand(id, command)
        
        // 更新命令状态
        const cmdIndex = this.pendingCommands.findIndex(cmd => 
          cmd.deviceId === id && cmd.command === command
        )
        
        if (cmdIndex >= 0) {
          if (res.code === 200) {
            this.pendingCommands[cmdIndex].status = 'success'
          } else {
            this.pendingCommands[cmdIndex].status = 'failed'
            this.pendingCommands[cmdIndex].error = res.message
          }
        }
        
        if (res.code === 200) {
          return true
        } else {
          message.error(res.message || '发送命令失败')
          return false
        }
      } catch (error) {
        console.error('发送设备命令失败:', error)
        
        // 更新命令状态
        const cmdIndex = this.pendingCommands.findIndex(cmd => 
          cmd.deviceId === id && cmd.command === command
        )
        
        if (cmdIndex >= 0) {
          this.pendingCommands[cmdIndex].status = 'failed'
          this.pendingCommands[cmdIndex].error = error.message
        }
        
        message.error('发送命令失败')
        return false
      }
    },
    
    // 清理过期命令（保留最近1小时的命令）
    cleanupPendingCommands() {
      const oneHourAgo = Date.now() - 3600000 // 1小时前
      this.pendingCommands = this.pendingCommands.filter(cmd => cmd.timestamp >= oneHourAgo)
    },
	
	// 删除硬件设备
	  async deleteDevice(deviceId) {
	    try {
	      const res = await api.hardware.deleteHardwareDevice(deviceId)
	      
	      if (res.code === 200) {
	        // 删除成功，不需要调用loadPrivateDevices
	        message.success('设备删除成功')
	        return true
	      } else {
	        message.error(res.message || '删除设备失败')
	        return false
	      }
	    } catch (error) {
	      console.error('删除设备失败:', error)
	      message.error('删除设备失败')
	      return false
	    }
	  },
    
    // 检查MAC地址是否已注册
    async checkMacAddress(macAddress) {
      try {
        const res = await api.hardware.checkMacAddress(macAddress)
        return res.code === 200 && res.data
      } catch (error) {
        console.error('检查MAC地址失败:', error)
        return false
      }
    }
  }
})